package org.xmx0632.connector.util.client;

import java.io.IOException;

import org.xmx0632.connector.util.Util;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.SslContextBuilder;
import io.netty.handler.ssl.util.InsecureTrustManagerFactory;

/**
 * Client for Test
 * 
 */
public class SslClient {

	static final String HOST = "127.0.0.1";
	static final int PORT = 2001;

	public static void main(String[] args) throws IOException, InterruptedException {
		final SslContext sslCtx = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE)
				.build();

		EventLoopGroup group = new NioEventLoopGroup();
		try {
			Bootstrap b = new Bootstrap();
			b.group(group).channel(NioSocketChannel.class).handler(new SslClientInitializer(sslCtx));

			// Start the connection attempt.
			Channel ch = b.connect(HOST, PORT).sync().channel();

			// String line = "床前明月光\r\n疑是地上霜\r\n举头望明月\r\n低头思故乡\r\n";
			String line = "{\"name\":\"demoMessage\"}\r\n";

			// Sends the received line to the server.
			ChannelFuture lastWriteFuture = ch.writeAndFlush(line);

			// Wait until all messages are flushed before closing the channel.
			if (lastWriteFuture != null) {
				lastWriteFuture.sync();
			}

			Util.sleep(10000);
		} finally {
			group.shutdownGracefully();
		}
	}

}
